import yaml
from .models import RemoteService
from .utils import config as config_util

class LocalSvcConfig:
    '''Application configs
    '''

    _config_path: str
    _config_abs_path: str
    _raw_config_map: dict
    projects: dict[str, RemoteService]

    def __init__(self, config_path):
        self._config_path = config_path
        self._config_abs_path = config_util.find_file(config_path)
        if self._config_abs_path is None:
            raise FileNotFoundError(config_path)
        with open(self._config_abs_path, 'r', encoding='utf-8') as st:
            self._raw_config_map = yaml.load(st, Loader=yaml.Loader)
        self._parse_all()

    def __get_path(self, *names):
        '''find path in dict
        '''
        node = self._raw_config_map # init pointer
        for name in names:
            if name in node:
                node = node[name]
            else:
                return None
        return node

    def _parse_projects(self) -> dict:
        ret = {}
        config = self.__get_path("projects")
        for (name, conf) in config.items():
            ret[name] = RemoteService(
                name,
                url=conf['url'],
                description=conf['description'] if 'description' in conf else None,
            )
        return ret

    def _parse_all(self):
        self.projects = self._parse_projects()

    def get_project(self, name: str) -> RemoteService:
        '''get project by name
        '''
        return self.projects[name] if name in self.projects else None

    def list_projects(self) -> list[RemoteService]:
        '''list all projects
        '''
        return list(self.projects.values())
